﻿using System;
using System.Windows;
using System.Windows.Threading;

namespace BattleforgeAssault
{
    public class MessageEventArgs : EventArgs
    {
        public string Message { get; set; }

        public MessageEventArgs(string message)
        {
            Message = message;
        }
    }

    /// <summary>
    /// Static class for sending messages throughout the application
    /// </summary>
    public static class Messager
    {
        /// <summary>
        /// The event to attach to in order to listen to all messages
        /// </summary>
        public static event EventHandler<MessageEventArgs> MessageEvent;

        /// <summary>
        /// If the messager is called from a thread other than the UI thread, this property must be set
        /// </summary>
        public static Dispatcher UIDispatcher { get; set; }

        /// <summary>
        /// Total number of errors that were raised during the lifetime of this messager
        /// </summary>
        public static int ErrorCount { get; set; }

        private static void RaiseMessage(string message)
        {
            var handler = MessageEvent; if (handler != null)
            {
                if (UIDispatcher != null && !UIDispatcher.CheckAccess())
                {
                    UIDispatcher.BeginInvoke(() => { handler(null, new MessageEventArgs(message)); });
                }
                else { handler(null, new MessageEventArgs(message)); }
            }
        }

        /// <summary>
        /// Send a message to all listeners
        /// </summary>
        /// <param name="format">A composite format string</param>
        /// <param name="args">An object array that contains 0 or more objects to format</param>
        public static void SendMessage(string format, params object[] args)
        {
            RaiseMessage(String.Format(format, args));
        }

        /// <summary>
        /// Send a message to all listeners with the prefix ERROR
        /// </summary>
        /// <param name="format">A composite format string</param>
        /// <param name="args">An object array that contains 0 or more objects to format</param>
        public static void SendError(string format, params object[] args)
        {
            ++ErrorCount;
            RaiseMessage(String.Format("ERROR: " + format, args));
        }
    }
}
